﻿using System;
using System.IO;
using System.Xml.Serialization;
using System.Collections.Generic;

namespace Paragon
{
    public static class CollectionExtension
    {
        private static XmlRootAttribute root;
        private static XmlSerializer serializer;

        static CollectionExtension()
        {
            root = new XmlRootAttribute("Entries");
            serializer = new XmlSerializer(typeof(List<CollectionEntry>), null, new Type[] { typeof(CollectionEntry) }, root, "http://paragon.codeplex.com/");
        }

        public static string ToXml<TKey, TValue>(this IDictionary<TKey, TValue> value)
        {
            StringWriter writer = new StringWriter();
            serializer.Serialize(writer, Convert<TKey, TValue>(value));

            return writer.ToString();
        }

        private static List<CollectionEntry> Convert<TKey, TValue>(IDictionary<TKey, TValue> value)
        {
            List<CollectionEntry> entries = new List<CollectionEntry>();
            foreach (KeyValuePair<TKey, TValue> pair in value)
            {
                try
                {
                    CollectionEntry entry = new CollectionEntry();
                    entry.Key = pair.Key.ToString();

                    if (pair.Value != null)
                        entry.Value = pair.Value.ToString();
                    entries.Add(entry);
                }
                catch
                {
                    // TODO: Logging
                }
            }

            return entries;
        }

        [Serializable]
        private class CollectionEntry
        {
            [XmlAttribute]
            public string Key { get; set; }

            [XmlElement]
            public string Value { get; set; }
        }
    }
}
